//
//  SWBasketPageSortViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/12.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWBasketPageSortViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate
{
    var sortedCompleteCallback:(()->Void)?
    
    private var _pages:[SWPageProduct] = []
    
    lazy private var _tableView:UITableView = UITableView()
    lazy private var _ascendingBtn:UIButton = UIButton(type: .system)
    lazy private var _descendingBtn:UIButton = UIButton(type: .system)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        _pages = SWTransactionManager.sharedManager().pages
        
        createNavigationLeftButton("取消", target: self, action: #selector(cancelBtnTapped))
        createNavigationRightButton("确定", target: self, action: #selector(confirmBtnTapped))
        
        let lastY:CGFloat = createTopToolbar()
        
        _tableView.frame = CGRectMake(0, lastY, view.width, view.height - lastY)
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex: 0xeceeef)
        _tableView.rowHeight = 120
        _tableView.isEditing = true
        view.addSubview(_tableView)
    }
    
    private func createTopToolbar() -> CGFloat
    {
        let bar:UIView = UIView()
        bar.backgroundColor = UIColor.lightGray
        bar.frame = CGRectMake(0, navigationBarBottom, view.width, 40)
        view.addSubview(bar)
        
        _ascendingBtn.setTitle("升序", for: .normal)
        _ascendingBtn.sizeToFit()
        _ascendingBtn.addTarget(self, action: #selector(ascendingBtnTapped), for: .touchUpInside)
        bar.addSubview(_ascendingBtn)
        
        _descendingBtn.setTitle("降序", for: .normal)
        _descendingBtn.sizeToFit()
        _descendingBtn.center = CGPointMake(_ascendingBtn.right + _descendingBtn.width, bar.height * 0.5)
        _descendingBtn.addTarget(self, action: #selector(descendingBtnTapped), for: .touchUpInside)
        bar.addSubview(_descendingBtn)
        
        let previewBtn:UIButton = UIButton(type: .system)
        previewBtn.setTitle("预览", for: .normal)
        previewBtn.sizeToFit()
        previewBtn.center = CGPointMake(bar.width - previewBtn.width, bar.height * 0.5)
        previewBtn.addTarget(self, action: #selector(previewBtnTapped), for: .touchUpInside)
        bar.addSubview(previewBtn)
        
        return bar.bottom
    }
    
    private func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _pages.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let Identifier:String = "SWBasketPageSortCell"
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: Identifier) as? SWBasketPageSortCell
        if cell == nil
        {
            cell = SWBasketPageSortCell(style: .default, reuseIdentifier: Identifier, cellWidth: view.width)
        }
        (cell as? SWBasketPageSortCell)?.product = _pages.valueAt(indexPath.row)
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle
    {
        return .none
    }
    
    //编辑状态下是否缩进
    func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool
    {
        return false
    }
    
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool
    {
        return true
    }
    
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
    {
        if let item = _pages.removeAtIndexSafely(sourceIndexPath.row)
        {
            _pages.insertSafely(item, atIndex: destinationIndexPath.row)
        }
        
        print(sourceIndexPath, "->", destinationIndexPath)
    }
    
    @objc private func cancelBtnTapped()
    {
        close()
    }
    
    @objc private func confirmBtnTapped()
    {
        //对数据进行检查，合格之后
        SWTransactionManager.sharedManager().pages = _pages
        sortedCompleteCallback?()
        close()
    }
    
    @objc private func ascendingBtnTapped()
    {
        _pages.sort(by: {$0.page.photoImportedTime < $1.page.photoImportedTime})
        _tableView.reloadData()
    }
    
    @objc private func descendingBtnTapped()
    {
        _pages.sort(by: {$0.page.photoImportedTime > $1.page.photoImportedTime})
        _tableView.reloadData()
    }
    
    @objc private func previewBtnTapped()
    {
        let pages:[SWPage] = _pages.map({$0.page})
        let viewController = SWPreviewViewController(pages: pages)
        present(viewController, animated: true, completion: nil)
    }
    
}
